<script>
import ConHeader from '@/components/conHeader/conHeader.vue';
import ConFooter from '@/components/conFooter/conFooter.vue';
import { paymentMethodArray } from '@/const';

export default {
  name: 'controlsCard',
  data() {
    const validateCarNumber = (rule, value, callback) => {
      const reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
      if (reg.test(value)) {
        return callback();
      } else {
        return callback(new Error('请输入正确的车牌'));
      }
    };
    const validatePhoneNumber = (rule, value, callback) => {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (reg.test(value)) {
        return callback();
      } else {
        return callback(new Error('请输入正确的手机号'));
      }
    };
    return {
      paymentMethodArray,
      loading: false,
      date: [],
      vehicleInfoRef: null,
      paymentInfoRef: null,
      cardDetail: {},
      // 车辆信息
      vehicleInfo: {
        // 车主姓名
        personName: '',
        // 联系方式
        phoneNumber: '',
        // 车牌号码
        carNumber: '',
        // 车辆品牌
        carBrand: '',
      },
      // 缴费信息
      paymentInfo: {
        // 支付金额
        paymentAmount: '',
        // 支付方式
        paymentMethod: '',
        // 有效时间开始
        cardStartDate: '',
        // 有效时间结束
        cardEndDate: '',
      },
      vehicleInfoRules: {
        personName: [
          { required: true, message: '请输入车主姓名', trigger: 'blur' },
        ],
        phoneNumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: validatePhoneNumber, trigger: 'blur' },
        ],
        carNumber: [
          { required: true, message: '请输入车牌号码', trigger: 'blur' },
          { validator: validateCarNumber, trigger: 'blur' },
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' },
        ],
      },
      paymentInfoRules: {
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' },
        ],
        paymentAmount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' },
        ],
      },

    };
  },
  methods: {
    // 用于派发action添加月卡的回调函数
    async handleAddCard() {
      try {
        const [cardStartDate, cardEndDate] = this.date;
        this.paymentInfo.cardStartDate = cardStartDate;
        this.paymentInfo.cardEndDate = cardEndDate;
        const addResult = await this.$store.dispatch('monthCardStore/addCardAction', { ...this.paymentInfo, ...this.vehicleInfo });
        this.$router.back();
        this.$message.success(addResult);
      } catch (error) {
        this.$message.error(error);
      }
    },
    // 用于派发action编辑月卡的回调函数
    async handleEditCard() {
      try {
        const [cardStartDate, cardEndDate] = this.date;
        this.paymentInfo.cardStartDate = cardStartDate;
        this.paymentInfo.cardEndDate = cardEndDate;
        const editResult = await this.$store.dispatch('monthCardStore/editCardAction', { ...this.vehicleInfo, ...this.paymentInfo });
        this.$router.back();
        this.$message.success(editResult);
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    // 用于派发action查看月卡的回调函数
    async handleViewCard() {
      if (this.controls === 'viewCard') {
        try {
          this.loading = true;
          const responseData = await this.$store.dispatch('monthCardStore/viewCardAction', this.$route.query.id);
          this.cardDetail = responseData;
        } catch (error) {
          this.$message.error(error.message);
        } finally {
          this.loading = false;
        }
      }
    },
    // 用于派发action续费月卡的回调函数
    async handleRenewCard() {
      try {
        const data = { cardStartDate: this.date[0], cardEndDate: this.date[1], paymentAmount: this.paymentInfo.paymentAmount, paymentMethod: this.paymentInfo.paymentMethod, carInfoId: this.vehicleInfo.carInfoId };
        const renewResult = await this.$store.dispatch('monthCardStore/renewCardAction', data);
        this.$router.back();
        this.$message.success(renewResult);
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    // 点击确定按钮的回调函数
    async handleSubmit() {
      const validateVe = await this.$refs.vehicleInfoRef.validate().catch(error => error);
      const validatePa = await this.$refs.paymentInfoRef.validate().catch(error => error);
      if (!validateVe) return;
      if (!validatePa) return;
      if (this.controls === 'addCard') {
        this.handleAddCard();
      } else if (this.controls === 'editCard') {
        this.handleEditCard();
      } else if (this.controls === 'viewCard') {
        this.handleViewCard();
      }
    },
    // 派发action获取月卡详情的回调函数
    async fetchCardDetail() {
      if (this.controls == 'editCard' || this.controls == 'renewCard') {
        const { personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod, cardStartDate, cardEndDate, carInfoId, rechargeId } = await this.$store.dispatch('monthCardStore/findCardAction', this.$route.query.id);
        this.vehicleInfo.personName = personName;
        this.vehicleInfo.phoneNumber = phoneNumber;
        this.vehicleInfo.carNumber = carNumber;
        this.vehicleInfo.carBrand = carBrand;
        this.vehicleInfo.carInfoId = carInfoId;
        this.vehicleInfo.rechargeId = rechargeId;
        this.paymentInfo.paymentAmount = paymentAmount;
        this.paymentInfo.paymentMethod = paymentMethod;
        this.date.push(cardStartDate);
        this.date.push(cardEndDate);
      }
    },
  },
  computed: {
    disabled() {
      return this.title === '续费月卡';
    },
    controls() {
      const { controls } = this.$route.query;
      return controls;
    },
    // 动态计算标题
    title() {
      if (this.controls === 'addCard') {
        return '添加月卡';
      } else if (this.controls === 'editCard') {
        return '编辑月卡';
      } else if (this.controls === 'viewCard') {
        return '查看月卡';
      } else if (this.controls === 'renewCard') {
        return '续费月卡';
      }
    },
  },
  mounted() {
    this.fetchCardDetail();
    this.handleViewCard();
  },
  components: { ConFooter, ConHeader },
};
</script>

<template>
  <div class="controls-card-container">
    <con-header :title="title"></con-header>

    <main class="controls-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form" v-if="controls==='addCard'||controls==='editCard'||controls==='renewCard'">
          <el-form label-width="100px" size="small" :model="vehicleInfo" :rules="vehicleInfoRules" ref="vehicleInfoRef">
            <el-form-item label="车主姓名" prop="personName">
              <el-input placeholder="请输入车主姓名" :disabled="disabled" v-model="vehicleInfo.personName"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input placeholder="请输入连联系方式" :disabled="disabled" v-model="vehicleInfo.phoneNumber" />
            </el-form-item>
            <el-form-item label="车牌号码" prop="carNumber">
              <el-input placeholder="请输入车牌号码" :disabled="disabled" v-model="vehicleInfo.carNumber"></el-input>
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input placeholder="请输入车辆品牌" :disabled="disabled" v-model="vehicleInfo.carBrand"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="info" v-else>
          <el-row>
            <el-col :span="12">
              <span>车主姓名: {{ cardDetail.personName }}</span>
            </el-col>
            <el-col :span="12">
              <span>联系方式: {{ cardDetail.phoneNumber }}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span>车牌号码: {{ cardDetail.carNumber }}</span>
            </el-col>
            <el-col :span="12">
              <span>车辆品牌: {{ cardDetail.carBrand }}</span>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="form-container">
        <div class="title">月卡缴费信息</div>
        <div class="form" v-if="controls==='addCard'||controls==='editCard'||controls==='renewCard'">
          <el-form label-width="100px" size="small" :model="paymentInfo" :rules="paymentInfoRules" ref="paymentInfoRef">
            <el-form-item label="有效日期">
              <el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input placeholder="请输入支付金额 " v-model="paymentInfo.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select placeholder="请选择支付方式" v-model="paymentInfo.paymentMethod">
                <el-option v-for="(item) in paymentMethodArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="table" v-else>
          <el-table :header-cell-style="{background:'#f4f6f8',color:'#000'}" :data="cardDetail.rechargeList" size="small" stripe border v-loading="loading" element-loading-text="拼命加载中">
            <el-table-column type="index" label="序号" align="center"></el-table-column>
            <el-table-column label="有效时间" align="center">
              <template #default="{row}">{{ row.cardStartDate }}-{{ row.cardEndDate }}</template>
            </el-table-column>
            <el-table-column prop="paymentAmount" label="支付金额" align="center"></el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式" align="center"></el-table-column>
            <el-table-column prop="createTime" label="办理时间" align="center"></el-table-column>
            <el-table-column prop="createUser" label="办理人" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
    </main>
    <con-footer v-if="controls!=='viewCard'">
      <el-button size="small">重置</el-button>
      <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
    </con-footer>
  </div>
</template>

<style scoped lang="scss">
.controls-main {
  background: #f4f6f8;
  padding: 20px 130px;

  .form-container {
    background-color: #fff;

    .title {
      height: 60px;
      line-height: 60px;
      padding-left: 20px;
    }

    .form {
      margin-bottom: 20px;
      padding: 20px 65px 24px;

      .el-form {
        display: flex;
        flex-wrap: wrap;

        .el-form-item {
          width: 50%;

          .el-select {
            width: 100%;
          }

          .el-date-editor {
            width: 100%;
          }
        }
      }
    }

    .table, .info {
      padding-left: 20px;
    }

    .table {
      padding-bottom: 10px;
    }

    .el-row {
      margin: 10px 0;

      .el-col {
        margin: 10px 0;
      }

      span {
        color: #9d9d9d;
      }
    }


  }

  .preview {
    img {
      width: 100px;
    }
  }

}

</style>
